from django.shortcuts import render, HttpResponse
from utils.tecent.sms import send_sms_single
import random
from django.conf import settings


def send_sms(request):
    """
    发送短信
    ?tpl=login ->登录：699164
    ?tpl=register ->注册：699165
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 9999)
    res = send_sms_single(15686948083, template_id, [code, ])
    if res['result'] == 0:
        return HttpResponse('短信发送成功')
    else:
        return HttpResponse(res['errmsg'])


from app01 import models
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'),])
    password = forms.CharField(label='密码',widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='重复密码',widget=forms.PasswordInput())
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['username','password','confirm_password','email','mobile_phone','code']

def register(request):
    form = RegisterModelForm()
    return render(request, 'register.html', {'form': form})
